﻿using System.Diagnostics;

/// <summary>
/// 执行命令
/// </summary>
public class CmdHelper
{
    static Process p;
    public static string ExeCommand(string commandText, string dir)
    {
        return ExeCommand(new string[] { commandText }, dir);
    }

    public static string ExeCommand(string[] commandTexts, string dir)
    {
        p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.CreateNoWindow = true;
        if (!string.IsNullOrEmpty(dir))
        {
            p.StartInfo.WorkingDirectory = dir;
        }
        string strOutput = null;
        try
        {
            p.Start();
            foreach (string item in commandTexts)
            {
                p.StandardInput.WriteLine(item);
            }
            p.StandardInput.WriteLine("exit");
            strOutput = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();
        }
        catch (Exception e)
        {
            strOutput = e.Message;
        }
        return strOutput;
    }

    public static void Kill()
    {
        p.Close();
        p.Kill();
    }
}
